ソースコード
#辞書練習課題の実装 Dictionary 2025/2/10
#coding:utf-8
import os
os.system("clear")
#練習問題1:お気に入りの本とその著者の辞書を作成してください。
Favorite_Books = {
# "A":{"著者":"", "ISBN":"", "出版社":"", "定価":2600, "出版年":2021},
# "B":{"著者":"", "ISBN":"", "出版社":"", "定価":2600, "出版年":2021},
"スマートフォンサイト実践デザイン入門": {"著者":["林久純","今野昭彦"], "ISBN":"978-4-7973-7242-7", "出版社":"SoftBank Creative", "定価":2600, "出版年":2013}
}
print(Favorite_Books)
print(f'『スマートフォンサイト実践デザイン入門』の著者は{Favorite_Books["スマートフォンサイト実践デザイン入門"]["著者"][0]}さんと{Favorite_Books["スマートフォンサイト実践デザイン入門"]["著者"][1]}さんです。')
#練習問題2:文字列内の各文字の出現頻度を数える関数を書いてください。
from collections import defaultdict
def count_chars(text):
char_count = defaultdict(int)
for char in text:
char_count[char] += 1
return dict(char_count)
text = "OpenAI is a private research organization that focuses on artificial intelligence (AI). The company's mission is to develop AI systems that are safe and beneficial to humanity. "
print(count_chars(text))
print(f'辞書のサイズ(charの個数)={len(count_chars(text))}')
#練習問題3:2つの辞書を1つにマージする関数を書いてください。
def merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
example1 = {"a":2,"b":1}
example2 = {"b":3,"c":4}
result = merge_dicts(example1, example2) #同じキーの場合、2番目の辞書を採用する
print(example1,example2)
print(result)
#練習問題4:辞書内で最大値を持つキーを見つけてください。
def find_key_with_max_value(dictionary):
if not dictionary:
return None # 辞書が空の場合はNoneを返す
return max(dictionary, key=dictionary.get)
#練習問題5:辞書内で最小値を持つキーを見つけてください。
def find_key_with_min_value(dictionary):
if not dictionary:
return None # 辞書が空の場合はNoneを返す
return min(dictionary, key=dictionary.get)
#練習問題2の出力結果
example = {'O': 1, 'p': 4, 'e': 16, 'n': 11, 'A': 3, 'I': 3, ' ': 27, 'i': 15, 's': 12, 'a': 15, 'r': 6, 'v': 2, 't': 12, 'c': 6, 'h': 5, 'o': 9, 'g': 2, 'z': 1, 'f': 4, 'u': 2, 'l': 5, '(': 1, ')': 1, '.': 2, 'T': 1, 'm': 4, 'y': 3, "'": 1, 'd': 2, 'b': 1}
result1 = find_key_with_max_value(example)
print(f'最大値をもつキーは{result1}です。{example[result1]}個です。')
result2 = find_key_with_min_value(example)
print(f'最大値をもつキーは{result2}です。{example[result2]}個です。')